# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def addTwoNumbers(self, l1, l2):
        l3 = ListNode(0)
        p = l3
        sum = 0
        while l1 or l2:
            if l1:
                if l2:
                    temp = l1.val+l2.val + sum
                    sum = 0
                    if temp <10:
                        p.next = ListNode(temp)
                        p = p.next
                        l1 = l1.next
                        l2 = l2.next
                    else:
                        p.next = ListNode(temp%10)
                        p = p.next
                        sum = 1
                        l1 = l1.next
                        l2 = l2.next
                else:
                    t = l1.val+sum
                    sum = 0
                    if t<10:
                        p.next = ListNode(t)
                        p = p.next
                        l1 = l1.next
                    else:
                        p.next = ListNode(t%10)
                        p = p.next
                        sum=1
                        l1 = l1.next
            else:
                t = l2.val + sum
                sum = 0
                if t < 10:
                    p.next = ListNode(t)
                    p = p.next
                    l2 = l2.next
                else:
                    p.next = ListNode(t % 10)
                    p = p.next
                    sum = 1
                    l2 = l2.next
        if sum==1:
            p.next = ListNode(1)
        return l3.next

